import { defineStore } from 'pinia'
import { ref, computed, onMounted, onUnmounted } from 'vue'
import type { GameState, HomeResources } from '../types/game'
import { StorageKey } from '../utils/enum'
import { useResourcesStore } from './resources'
import { useBuildingsStore } from './building'
import { useLogStore } from './log'
import dayjs from 'dayjs'
import { usePokemonStore } from './pokémonWild'
import { usePokemonAllStore } from './pokemonAll'
import { useCapturedPokemonStore } from './capturedPokemon'
import { useAbilitiesStore } from './abilities'

export const useGameStore = defineStore('game', () => {
  // 游戏状态
  const gameState = ref<GameState>({
    isRunning: false,
    lastSaved: Date.now(),
    lastTick: Date.now(),
  })

  const logStore = useLogStore()
  const resourcesStore = useResourcesStore()
  const buildingStore = useBuildingsStore()
  const pokemonStore = usePokemonStore()
  const pokemonAllStore = usePokemonAllStore()
  const capturedPokemonStore = useCapturedPokemonStore()
  const abilitiesStore = useAbilitiesStore()

  const initData = async () => {
    pokemonAllStore.initData()
    abilitiesStore.initData()
    await resourcesStore.initData()
    await buildingStore.initData()
    await capturedPokemonStore.init()
  }

  const startGame = async () => {
    gameState.value.isRunning = true
    gameState.value.lastTick = Date.now()
    await initData()
  }

  // 游戏循环更新
  function update() {
    if (!gameState.value.isRunning) return

    resourcesStore.update()
    pokemonStore.update()

    // 检查是否需要自动保存
    const currentTime = Date.now()
    /* if (currentTime - gameState.value.lastSaved >= DEFAULT_SETTINGS.autoSaveInterval) {
     console.log(123);
     
      gameState.value.lastSaved = currentTime
    } */

    gameState.value.lastTick = currentTime
  }

  // 暂停游戏
  function pauseGame() {
    gameState.value.isRunning = false
  }

  // 重置游戏
  function resetGame() {
    gameState.value = {
      isRunning: false,
      lastSaved: Date.now(),
      lastTick: Date.now(),
    }
  }

  return {
    update,
    startGame,
    pauseGame,
    resetGame,
    gameState,
  }
})
